﻿using DG.Tweening;

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class UIBattlePlayer : UIObject
{
    public Text[] textDices;
    public GameObject diceRoot;
    public GameObject cup;
    public Text textPlayer;
    public UIBattlePlayerHand playerHand;
    public UIBattlePlayerChallenge playerChallenge;
    public UIBattlePlayerChat playerChat;
    public UIBattlePlayerDice playerDice;
    private Dictionary<DiceType, Text> _diceType2Text;
    public GameObject blockView;
    protected override void Awake()
    {
        base.Awake();
        _diceType2Text = new Dictionary<DiceType, Text>();
        for (int i = (int)DiceType.One; i <= (int)DiceType.Six; i++)
        {
            _diceType2Text[(DiceType)i] = textDices[i];
        }
        //ShowDice(false);
    }

    protected override void OnDestroy()
    {
        base.OnDestroy();
        Unbind();
    }
    protected override void onVisible()
    {
        Facade.Instance.RegistNetEvent(nameof(actionbattle_rsp), OnHandleActionbattleRsp);
    }

    protected override void OnInvisible()
    {
        Facade.Instance.UnRegistNetEvent(nameof(actionbattle_rsp), OnHandleActionbattleRsp);
    }

    private DataBattlePlayer _dataBattlePlayer;
    public void Bind(DataBattlePlayer data)
    {
        playerHand?.Bind(data);
        playerChallenge?.Bind(data);
        playerChat?.Bind(data);
        _dataBattlePlayer = data;
        _dataBattlePlayer.OnStateChangeHandle += OnStateChangeHandle;
        _dataBattlePlayer.OnPlayerExitBattle += OnPlayerExitBattle;

        if (data.GetUserId() == DataPlayer.Instance.userId)
        {
            textPlayer.color = Color.green;
            textPlayer.text = "本人:" + data.GetUserName();
        }
        else
        {
            textPlayer.text = data.GetUserName();
        }

        OnStateChangeHandle(_dataBattlePlayer.GetState(), _dataBattlePlayer.GetUserId(), _dataBattlePlayer.GetUserId());
        Refresh();
    }

    public void Unbind()
    {
        playerHand?.Unbind();
        playerChallenge?.Unbind();
        playerChat?.Unbind();
        _dataBattlePlayer.OnStateChangeHandle -= OnStateChangeHandle;
        _dataBattlePlayer.OnPlayerExitBattle -= OnPlayerExitBattle;
        _dataBattlePlayer = null;
    }

    private void Refresh()
    {
        //设置骰子数目
        var diceTypeList = _dataBattlePlayer.GetDiceTypes();
        for (int i = 0; i < diceTypeList.Count; i++)
        {
            if(i < playerDice.items.Length)
            {
                playerDice.items[i].SetDiceType(diceTypeList[i]);
            }
        }

    }

    public void OnButtonCupClick()
    {
        if(this._dataBattlePlayer.GetUserId() != DataPlayer.Instance.userId)
        {
            UITips.Instance.Show("不能秘密查看自己骰子");
            return;
        }
        
        var req = new actionbattle();
        req.type = ActionType.LookByMySelf;
        req.touid = _dataBattlePlayer.GetUserId();
        WebSocketClient.Instance.SendSerialize(req);
    }

    public void OnButtonShakeClick(Button button)
    {
        var req = new actionbattle();
        req.type = ActionType.Shake;
        req.touid = _dataBattlePlayer.GetUserId();
        req.content = _dataBattlePlayer.GenerateRandomDiceType();
        WebSocketClient.Instance.SendSerialize(button, req);
    }

    public void OnButtonGlanceClick(Button button)
    {
        //秘密查看自己的塞子（零时代码）
        if(_dataBattlePlayer.GetUserId() == DataPlayer.Instance.userId)
        {
            var req1 = new actionbattle();
            req1.type = ActionType.LookByMySelf;
            req1.touid = _dataBattlePlayer.GetUserId();
            WebSocketClient.Instance.SendSerialize(button, req1);
            return;
        }

        var req = new actionbattle();
        req.type = ActionType.Glance;
        req.touid = _dataBattlePlayer.GetUserId();
        WebSocketClient.Instance.SendSerialize(button, req);
    }

    public void OnButtonOpenClick(Button button)
    {
        var req = new actionbattle();
        req.type = ActionType.Open;
        req.touid = _dataBattlePlayer.GetUserId();
        WebSocketClient.Instance.SendSerialize(button, req);
    }

    public void OnButtonCloseClick(Button button)
    {
        var req = new actionbattle();
        req.type = ActionType.Close;
        req.touid = _dataBattlePlayer.GetUserId();
        WebSocketClient.Instance.SendSerialize(button, req);
    }

    private void OnHandleActionbattleRsp(System.Object data)
    {
        var rsp = data as actionbattle_rsp;
        if (rsp.ret != NetErrorCode.None)
        {
            UITips.Instance.Show("出错了:" + rsp.ret + " " + rsp.reason);
        }
    }

    private void OnStateChangeHandle(BattlePlayerState state, string fromUserId, string toUserId)
    {
        switch (state)
        {
            case BattlePlayerState.Close:
                ResetCupPos();
                ShowDice(_dataBattlePlayer.IsCanShowDice());
                cup.transform.DOLocalRotateQuaternion(Quaternion.Euler(0, 0, 0), 0.2f);//合上盖子

                //修改骰子
                Refresh();
                break;
            case BattlePlayerState.Shake:
                ResetCupPos();
                SoundMgr.Instance.PlayEffect("Shake");

                ShowDice(_dataBattlePlayer.IsCanShowDice());

                cup.transform.DOLocalRotateQuaternion(Quaternion.Euler(0, 0, 0), 0.2f);//合上盖子

                //来回摇
                Sequence s = DOTween.Sequence();
                s.Append(cup.transform.DOLocalMoveX(-100, 0.1f));
                s.Append(cup.transform.DOLocalMoveX(100, 0.2f));
                s.Append(cup.transform.DOLocalMoveX(0, 0.1f));
                s.SetLoops(4, LoopType.Yoyo);

                //修改骰子
                Refresh();
                break;
            case BattlePlayerState.Open:
                ResetCupPos();
                SoundMgr.Instance.PlayEffect("Open");
                ShowDice(_dataBattlePlayer.IsCanShowDice());
                cup.transform.DOLocalRotateQuaternion(Quaternion.Euler(0, 0, 90), 0.2f);//打开盖子

                //修改骰子
                Refresh();
                break;
            case BattlePlayerState.Glance:
                ResetCupPos();
                ShowDice(_dataBattlePlayer.IsCanShowDice());
                cup.transform.DOLocalRotateQuaternion(Quaternion.Euler(0, 0, 30), 0.2f);//轻微打开盖子

                //修改骰子
                Refresh();
                break;
            case BattlePlayerState.LookByMySelf:
                ResetCupPos();
                ShowDice(_dataBattlePlayer.IsCanShowDice());//别人看不到自己的骰子
                cup.transform.DOLocalRotateQuaternion(Quaternion.Euler(0, 0, 10), 0.2f);//轻微打开盖子

                //如果是自己，就挡住筛子
                if(DataPlayer.Instance.userId == this._dataBattlePlayer.GetUserId())
                    blockView.SetActive(true);

                //修改骰子
                Refresh();
                break;
            default:
                Debug.LogError("unhandle state:" + state);
                break;
        }
        
    }

    private void ResetCupPos()
    {
        var trans = cup.GetComponent<RectTransform>();
        trans.anchoredPosition3D = Vector3.zero;
        blockView.SetActive(false);
    }
    private void OnPlayerExitBattle(string reason)
    {
        string str;
        switch (reason)
        {
            case "escape":
                str = "逃离";
                break;
            case "offline":
                str = "离线";
                break;
            case "online":
                str = "回来";
                break;
            default:
                str = reason;
                break;
        }

        textPlayer.text = _dataBattlePlayer.GetUserName() + ":" + str;
    }

    private void ShowDice(bool isShow)
    {
        diceRoot.SetActive(isShow);
    }

    private bool IsShowDice()
    {
        return diceRoot.activeSelf;
    }

    public void SetShowIndex(int showIndex)
    {
        this.transform.SetParent(UIBattle.Instance.playerRoots[showIndex].transform, false);
        var parent = playerHand.transform.parent.GetComponent<RectTransform>();
        var oldPosition = parent.anchoredPosition;
        if (showIndex > 4)
        {
            oldPosition.x = Mathf.Abs(oldPosition.x) * -1;
            parent.anchoredPosition = oldPosition;
        }
    }
}
